from database import SessionLocal
from models import TreeData
from sqlalchemy import func

def verify_data():
    db = SessionLocal()
    
    try:
        # 总记录数
        total_count = db.query(TreeData).count()
        print(f"数据库总记录数: {total_count}")
        
        # 树种统计
        print("\n=== 树种统计 ===")
        species_stats = db.query(TreeData.species, func.count(TreeData.id)).group_by(TreeData.species).all()
        for species, count in species_stats:
            print(f"{species}: {count} 条记录")
        
        # 检尺类型统计
        print("\n=== 检尺类型统计 ===")
        inspection_stats = db.query(TreeData.inspection_type, func.count(TreeData.id)).group_by(TreeData.inspection_type).all()
        for inspection_type, count in inspection_stats:
            print(f"{inspection_type}: {count} 条记录")
        
        # 样木号范围
        print("\n=== 样木号范围 ===")
        min_id = db.query(func.min(TreeData.sample_id)).scalar()
        max_id = db.query(func.max(TreeData.sample_id)).scalar()
        print(f"样木号范围: {min_id} - {max_id}")
        
        # 胸径统计
        print("\n=== 胸径统计 ===")
        avg_2024 = db.query(func.avg(TreeData.diameter_2024)).scalar()
        avg_2025 = db.query(func.avg(TreeData.diameter_2025)).scalar()
        print(f"2024年平均胸径: {avg_2024:.2f} cm")
        print(f"2025年平均胸径: {avg_2025:.2f} cm")
        
        # 坐标范围
        print("\n=== 坐标范围 ===")
        min_x = db.query(func.min(TreeData.x)).scalar()
        max_x = db.query(func.max(TreeData.x)).scalar()
        min_y = db.query(func.min(TreeData.y)).scalar()
        max_y = db.query(func.max(TreeData.y)).scalar()
        print(f"X坐标范围: {min_x:.6f} - {max_x:.6f}")
        print(f"Y坐标范围: {min_y:.6f} - {max_y:.6f}")
        
        # 显示前5条记录作为样本
        print("\n=== 前5条记录样本 ===")
        sample_records = db.query(TreeData).limit(5).all()
        for record in sample_records:
            print(f"样木号: {record.sample_id}, 树种: {record.species}, 检尺类型: {record.inspection_type}")
            print(f"  2024胸径: {record.diameter_2024}, 2025胸径: {record.diameter_2025}")
            print(f"  坐标: ({record.x}, {record.y})")
            print()
        
    except Exception as e:
        print(f"验证过程中出现错误: {e}")
    finally:
        db.close()

if __name__ == "__main__":
    verify_data() 